package com.by.exception;

import com.by.result.Result;
import com.by.result.ResultCode;
import com.by.validate.ValidationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器，用于处理应用程序中抛出的异常。
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    public Result<String> handleException(Exception e) {
        log.error("未捕获异常：", e);
        return Result.error(
                ResultCode.FAIL,
                e.getMessage() == null ? "服务器异常" : e.getMessage()
        );
    }

    @ExceptionHandler(ValidationException.class)
    public Result<String> handlerValicationException(ValidationException e) {
        //注意 如果不打印异常栈信息  控制台就不会显示
        log.error(e.getMessage());
        log.error("验证失败:"+e.getErrorField());
        return Result.error(ResultCode.FAIL, e.getErrorField().toString());
    }

    @ExceptionHandler(BusinessException.class)
    public Result<String> handlerBusinessException(BusinessException e){
        return Result.error(ResultCode.FAIL, e.getMessage());
    }

}